//
//  ITInputView.m
//  InTubePro
//
//  Created by seven on 2020/6/11.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITInputView.h"
@interface ITInputView ()<YYTextKeyboardObserver, UITextViewDelegate>{
    
}

@end

@implementation ITInputView

+ (instancetype)shareView{
    static ITInputView *_inputView = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _inputView = [ITInputView initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 50)];
        [UIApplication.sharedApplication.keyWindow addSubview:_inputView];
    });
    return _inputView;
}

- (void)initViews{
    [super initViews];
    self.backgroundColor = [UIColor colorWithHex:0xffffff alpha:1];
    _textView = [UITextView initWithFrame:self.bounds];
    //_textView.maxLength = 200;
    _textView.textContainerInset = UIEdgeInsetsMake(16, 14, 16, 14);
    //[_textView setMaskCornerRadius:22];
    //_textView.backgroundColor = [UIColor colorWithHex:0xffffff alpha:1];
    _textView.font = MediumFontWithSize(16);
    _textView.returnKeyType = UIReturnKeySend;
    //_textView.keyboardAppearance = UIKeyboardAppearanceDark;
    //[_textView addTarget:self action:@selector(onSendAction) forControlEvents:(UIControlEventEditingDidEndOnExit)];
    _textView.textColor = COLOR_333333;
    _textView.delegate = self;
    _textView.tintColor = ColorWithHex(0xC9A718);
    //_textView.leftView = [BaseView initWithFrame:CGRectMake(0, 0, 21, _textView.height)];
    //_textView.leftViewMode = UITextFieldViewModeAlways;
    
    UILabel *lbl = _textView.placeholderLabel;
    lbl.font = _textView.font;
    lbl.textColor = COLOR_999999;
    lbl.text = LocalTitle(@"You must have something to say…");
    //_textView.attributedPlaceholder = [NSMutableAttributedString generateAttriuteStringWithStr: LocalTitle(@"You must have something to say…") WithColor:COLOR_999999 WithFont:_textView.font];
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 3;// 字体的行间距
    NSDictionary *attributes = @{NSForegroundColorAttributeName: _textView.textColor,
                                 NSFontAttributeName:_textView.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    _textView.typingAttributes = attributes;
    //_textView.placeholderLabel.origin = CGPointMake(14, 10);
    [self addSubview:_textView];
}

- (instancetype)showWithDelegate:(id<ITInputViewDelegate>)delegate{
    if (_delegate != delegate) {
        _textView.text = nil;
    }
    self.centerX = self.superview.width/2;
    _delegate = delegate;
    
    [self becomeFirstResponder];
    return self;
}

- (void)hideView:(BOOL)clear{
    if (clear) {
        _textView.text = nil;
    }
    self.customAction = nil;
    [self resignFirstResponder];
}

- (BOOL)becomeFirstResponder{
    [UIApplication.sharedApplication.keyWindow addSubview:self];
    [YYTextKeyboardManager.defaultManager addObserver:self];
    return [_textView becomeFirstResponder];
}

- (BOOL)isFirstResponder{
    return _textView.isFirstResponder;
}

- (BOOL)resignFirstResponder{
    return [_textView resignFirstResponder];
}

- (void)keyboardChangedWithTransition:(YYTextKeyboardTransition)transition{
    CGRect frame = self.frame;
    BOOL show = transition.toVisible;
    if (show) {
        self.hidden = NO;
        CGRect rect = [self.superview convertRect:transition.toFrame fromView:UIApplication.sharedApplication.keyWindow];
        frame.origin.y = CGRectGetMinY(rect) - frame.size.height;
    }else {
        _timestamp = 0;
        frame.origin.y =  self.superview.height;
        if([_delegate respondsToSelector:@selector(onInputViewHide)])[_delegate onInputViewHide];
    }
    
    [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
        self.frame = frame;
    } completion:^(BOOL finished) {
        if (finished) {
            if (!show) {
                [YYTextKeyboardManager.defaultManager removeObserver:self];
                self.hidden = YES;
            }
        }
    }];
}


- (NSString *)text{
    NSString *text = _textView.text;
    return text.stringByTrim;
}

#pragma mark - textViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
    
    NSString *text = textView.text;
    
    if (text.length == 1) {
        if ([text isEqualToString:@" "] || [text isEqualToString:@"\n"]) {
            textView.text = @"";
            return;
        }
    }
    
    int _maxLength = 300;
    // 只有当maxLength字段的值不为无穷大整型也不为0时才计算限制字符数.
    if (text.length > 0) {
        
        if (!textView.markedTextRange && text.length > _maxLength) {
            textView.text = [textView.text substringToIndex:_maxLength]; // 截取最大限制字符数.
            [self.undoManager removeAllActions]; // 达到最大字符数后清空所有 undoaction, 以免 undo 操作造成crash.
            [AppUtils showInfo:LocalTitle(@"Can not input more!") position:CSToastPositionCenter];
        }
    }
    
    
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.width, 1000)];
    
    
    int height = size.height;
    _textView.height = height;
    
    CGRect rect = self.frame;
    rect.origin.y -= height-rect.size.height;
    rect.size.height = height;
    self.frame = rect;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        if([_delegate respondsToSelector:@selector(onSendAction)])[_delegate onSendAction];
        return NO;
    }
    return YES;
}

@end
